<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection" :scroll="{ x: false }" :loading="loading">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" v-auth="'slt:orderSearchExport:exportXls'" preIcon="ant-design:export-outlined"
          @click="exportOrderXls('1')"> 导出订单明细</a-button>
          <a-button type="primary" v-auth="'slt:orderSearchExport:exportXls'" preIcon="ant-design:export-outlined"
          @click="exportOrderXls('2')"> 导出订单</a-button>
          <a-spin size="large" :spinning="exportLoading"></a-spin>
        <j-upload-button name="file" v-auth="'slt:orderquery:afterorderimport'" type="primary"
          preIcon="ant-design:import-outlined" @click="importAfterOrder">上传售后单</j-upload-button>

        <a-button type="default" v-auth="'slt:orderquery:afterorderimporttemplate'"
          @click="handleExportXls('售后单导入模版', '/xl/template/downloadTemplateXls?template=importAfterOrder')">
          <Icon icon="line-md:download-off-loop" />下载售后单导入模板
        </a-button>

        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="handleBatchCreateKMOrder"
                v-if="hasPermission('slt:orderquery:batchcreatekmorder')">
                <Icon icon="token-branded:perp"></Icon>
                批量回传快麦
              </a-menu-item>

            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>

      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
        <template v-if="column.dataIndex === 'orderCode'">
          <!--订单运输类型-->

          {{ text }}<a href="javascript:void(0)" @click="copys(text)">
            <Icon icon="solar:copy-outline"></Icon>
          </a>
          <div v-if="record.kmSid">Sid：{{ record.kmSid }}<a href="javascript:void(0)" @click="copys( record.kmSid )">
              <Icon icon="solar:copy-outline"></Icon>
            </a></div>
          <p>
            <a-tag v-if="record.deliveryWay == '1'" color='red'>城配</a-tag>
            <a-tag v-else-if="record.deliveryWay == '2'" color='green'>一件代发</a-tag>
          </p>
        </template>
      </template>
      <template #orderDataRender="{ text, record }">
        <div>商品数量：{{ record.totalNum }}个/{{ record.detailNum }}种</div>
        <div>订单金额：{{ record.totalAmount }}</div>
        <div>售后金额：{{ record.totalAfterAmount }}</div>
        <div>应收金额：{{ record.totalRealAmount }}</div>
        <div v-if="record.paymentAmount" style="background-color:#f00056;">实收金额：{{ record.paymentAmount }}</div>
      </template>
      <template #receiptInfoRender="{ text, record }">
        <div>门店编号：{{ record.storeCode }}</div>
        <div>门店名称：{{ record.storeName }}</div>
        <div>门店类型：{{ record. storeType }}</div>
      </template>
      <template #createInfoRender="{ text, record }">
        <div>创建人：{{ record.createBy }}</div>
        <div>创建时间：{{ record.createTime }}</div>
        <div v-if="record.paymentTime" style="color:red;">支付时间：{{ record.paymentTime }}</div>
        <div v-if="record.orderNotes">订单备注：{{ record.orderNotes }}</div>
      </template>
      <template #orderStatusSlots="{ text, record }">
        <a-tag v-if="record.orderStatus == '待提交'" color='#CCCCCC'>{{ text }}</a-tag>
        <a-tag v-if="record.orderStatus == '待支付'" color='#FFA500'>{{ text }}</a-tag>
        <a-tag v-if="record.orderStatus == '待审核'" color='#FFD700'>{{ text }}</a-tag>
        <a-tag v-if="record.orderStatus == '待发货'" color='#ADD8E6'>{{ text }}</a-tag>
        <a-tag v-if="record.isDebt == '欠款送审'" color='#ff2d51'>{{ record.isDebt }}</a-tag>
        <a-tag v-if="record.orderStatus == '待收货'" color='#40E0D0'>{{ text }}</a-tag>
        <a-tag v-if="record.orderStatus == '已收货'" color='#2E8B57'>{{ text }}</a-tag>
      </template>
      <template #auditInfoRender="{ text, record }">
        <a-tag v-if="record.auditState == '0'" color='yellow'>审批状态：{{ record.auditState_dictText }}</a-tag>
        <a-tag v-if="record.auditState == '1'" color='green'>审批状态：{{ record.auditState_dictText }}</a-tag>
        <a-tag v-if="record.auditState == '2'" color='red'>审批状态：{{ record.auditState_dictText }}</a-tag>
        <a-tag v-if="record.auditState == '-1'" color='blue'>审批状态：{{ record.auditState_dictText }}</a-tag>
        <div>审核时间：{{ record.auditTime }}</div>
        <div>审核人：{{ record.auditBy }}</div>
        <div>审核意见：{{ record.auditNote }}</div>
      </template>
      <template #payInfoRender="{ text, record }">
        <a-tag v-if="record.paymentState == '-1' " color='red'>支付状态：{{ record.paymentState_dictText }}</a-tag>
        <a-tag v-if="record.paymentState == '1'" color='green'>支付状态：{{ record.paymentState_dictText }}</a-tag>
        <div v-if="record.paymentState == '1'">支付时间：{{ record.paymentTime }}</div>
        <div v-if="record.paymentState == '1' ">支付金额：{{ record.paymentAmount }}</div>
      </template>
      <template #shipmentInfoRender=" { text, record }">
        <a-tag v-if="record.shipmentState == '0'" color='red'>发货状态：{{ record.shipmentState_dictText }}</a-tag>
        <a-tag v-if="record.shipmentState == '1'" color='green'>发货状态：{{ record.shipmentState_dictText }}</a-tag>
        <a-tag v-if="record.shipmentState == '2'" color='yellow'>发货状态：{{ record.shipmentState_dictText }}</a-tag>
        <div>发货时间：{{ record.shipmentTime }}</div>
      </template>
      <template #deliveryCodeSlot="{ text, record }">
        <div v-for="(item, index) in record.deliveryCodes?.split(',')">

          <a href="javascript:void(0)" @click="handleDetailS(record.orderCode, item)">{{ item }}
            <Icon icon="icon-park:click" />
          </a>
        </div>
      </template>
      <template #expandedRowRender="{ record }">
        <div>收件人：{{ record.receiptName }} - {{ record.receiptPhone }}</div>
        <div>地址：{{ getAreaTextByCode(record.receiptZone) }} {{ record.receiptAddress }} </div>
        <div v-if="record.deliveryCodes"> 物流单号：
          <a-tag v-for="(item, index) in record.deliveryCodes?.split(',')">

            <a href="javascript:void(0)" @click="handleDetailS(record.orderCode, item)">{{ item }}
              <Icon icon="icon-park:click" />
            </a>
          </a-tag>
        </div>
      </template>

      <template #expandColumnTitle>
        <span style="color: red">更多</span>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <XlCustomerOrdeModal @register="registerModal" @success="handleSuccess"></XlCustomerOrdeModal>
    <AftersaleAddModal @register="registerEditModal" @success="handleSuccess"></AftersaleAddModal>
    <AllFlowTabDrawer @register="registerDrawer" />

    <!-- 表单区域 -->
    <XlCustomerOrdeDetailNewModal @register="registeNewModal" @success="handleSuccess"></XlCustomerOrdeDetailNewModal>

    <uploadStamentModal @register="registerUploadStamentModal" @success="handleSuccess"></uploadStamentModal>

    <LogisticDetail @register="registerDetailModal1"></LogisticDetail>

    <billLogDraw @register="registerBillLogDraw"></billLogDraw>

    <!-- 表单区域 -->
    <AllModal @register="submitPaymentModal" :schemas="zhifupinzhengFormSchema" :apiUrl="submitPayment" :height="320"
      @success="handleSuccess" />

  </div>
</template>

<script lang="ts" name="lx-xlCustomerOrde" setup>
import { ref, reactive, onMounted, unref, computed } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage'
import { useModal } from '/@/components/Modal';
import XlCustomerOrdeModal from './components/XlCustomerOrdeModal.vue'
import XlCustomerOrdeDetailNewModal from './components/XlCustomerOrdeDetailNewModal.vue'
import LogisticDetail from '../logicmana/components/LogisticDetail.vue';
import { queryColumns, queryFormSchema, uniFormSchema, zhifupinzhengFormSchema } from './XlCustomerOrde.data';
import { queryList, exportPdfStream, copyToCreate, deleteOne, createKMOrder, submitPayment,createWDTOrder,handleRefreshLogistics ,exportStatementPDF} from './XlCustomerOrde.api';
import { useUserStore } from '/@/store/modules/user';
import { getAreaTextByCode } from '/@/components/Form/src/utils/Area';
import { useMessage } from "/@/hooks/web/useMessage";
import { useMethods } from '/@/hooks/system/useMethods';
import { useDrawer } from '/@/components/Drawer';
import AllFlowTabDrawer from './components/AllFlowTabDrawer.vue';
import AllModal from './components/AllModal.vue';
import AftersaleAddModal from '/@/views/xl/aftersale/components/AftersaleAddModal.vue';
import { Tag } from 'ant-design-vue';
import billLogDraw from './billLogDraw.vue';
const { handleExportXls, handleImportXls } = useMethods();
import { usePermission } from '/@/hooks/web/usePermission';
const { hasPermission } = usePermission();
const { createConfirm, createMessage } = useMessage();
const queryParam = reactive<any>({});
const checkedKeys = ref<Array<string | number>>([]);
const userStore = useUserStore();
const searchSchema = ref<any>(queryFormSchema);

const exportLoading = ref(false);
//注册model
const [registerModal, { openModal }] = useModal();
const [registerEditModal, registerEditUseModal] = useModal();
const [registeNewModal, openNewModel   ] = useModal();

const [registerDrawer, { openDrawer }] = useDrawer();
const loading = ref(false); 
const [registerDetailModal1, detailModel1] = useModal();
const [registerBillLogDraw, openBillLogDraw ] = useDrawer();

//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '订单列表',
    api: queryList,
    columns: queryColumns,
    canResize: false,
    formConfig: {
      schemas: uniFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [
      ],
      fieldMapToTime: [
        ['createTime', ['createTime_begin', 'createTime_end'], 'YYYY-MM-DD'],
        ['paymentTime', ['paymentTime_begin', 'paymentTime_end'], 'YYYY-MM-DD'],
        ['auditTime', ['auditTime_begin', 'auditTime_end'], 'YYYY-MM-DD'], 
      ],
     
    },
    actionColumn: {
      width: 250,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    },
    beforeFetch: (params) => {
      return Object.assign(params, queryParam);
    },
    // 显示底部合计
    showSummary: true,
    // 底部合计计算方法
    summaryFunc: onSummary
    
  },
  exportConfig: {
    name: "xl_product_info",
    url: "",
    params: queryParam,
  },
})
/**
  * 计算合计
  * @param tableData
  */
import { mapTableTotalSummary } from '/@/utils/common/compUtils';
function onSummary(tableData: Recordable[]) {
  // 可用工具方法自动计算合计
  const totals = mapTableTotalSummary(tableData, ['totalAmount']);
  return [{
    _row: '合计',
    _index: '合计',
    storeName: "订单金额："+totals.totalAmount.toFixed(2) +"元"
  }
  ];
}
const [registerTable, { reload, getForm }, { rowSelection, selectedRowKeys, selectedRows }] = tableContext



function importAfterOrder(file) {
  handleImportXls(file, '/xl/xlCustomerAftersale/importExcel', '').then(() => {
    handleSuccess();
  });
}
/**
 * 详情
*/
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  })
}

//物料查询
function handleQueryTrack(record) {
  openDrawer(true, {
    orderCode: record?.orderCode,
  });
}
//导出对账单 pdf
async function handleExportStatementPDF(record) {
  loading.value = true;
  await exportStatementPDF(record);
  loading.value = false;
}

/**
 * PDF导出
 */
async function handleExcelConfigId(record, excelConfigId,fileName) {
  var info = await exportPdfStream({
    excelConfigId: excelConfigId,//"1011051575872913408",
    queryParam: {
      receiptZone: getAreaTextByCode(record?.receiptZone),
      orderCode: record?.orderCode,
      token: userStore.getToken,
      pageNo: "1",
      pageSize: 10,
      currentPageNo: "1",
      currentPageSize: 10
    }
  })

  // 创建 Blob 对象
  const blob = new Blob([info], { type: 'application/pdf' });

  // 创建下载链接
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = fileName; //'订单出库单.pdf'; // 设置下载文件名
  document.body.appendChild(link);
  link.click(); // 触发下载
  document.body.removeChild(link); // 移除链接

  // 释放 Blob URL
  URL.revokeObjectURL(link.href);
}

/**
* 发起售后
*/
function handleAddAftersale(record: Recordable) {
  registerEditUseModal.openModal(true, {
    record,
    isUpdate: false,
    showFooter: true,
  });
}

/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
   * 操作栏
   */
function getTableAction(record) {
  return [
    
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
    {
      label: '回传快麦',
      onClick: handleCreateKMOrder.bind(null, record),
      auth: 'slt:orderquery:createkmorder',
    },
    {
      label: '对账单导出',
      //onClick: handleExportStatementPDF.bind(null, record),
     onClick: handleExcelConfigId.bind(null, record, '1015774270700802048', (record.receiptName +"-"+ String(record.totalRealAmount))+"对账单.pdf"),
      auth: 'lx:xl_customer_orde:pdfExport'
    },
    // {
    //   label: '回传WDT',
    //   onClick: handleCreateWDTOrder.bind(null, record),
    //   auth: 'slt:orderquery:createkmorder',
    // },
  ]
}
function handleDetailS(orderCode, logiStr) {
  let s = logiStr.split(":");
  let cord = { orderCode: orderCode, logiCom: s[0], logiOrder: s[1] };


  detailModel1.openModal(true, {
    record: cord,
  });
}
function handleLog(record) {
  openBillLogDraw.openDrawer(true,{
    orderCode:record.orderCode
  })
}
function handleCopyToCreate(record) {
  copyToCreate(record);
  reload();
}
async function handleCreateWDTOrder(record) {
  if (record.kmSid) {
    createConfirm({
      iconType: 'info',
      title: '重新回传',
      content: '已有Sid，确定重新回传嘛？',
      onOk: async () => {
        loading.value = true;
        await createWDTOrder({ orderids: record.id }).then(() => {
          reload();
        }).finally(() => {
          // 这里是无论成功或失败都会执行的方法，在这里关闭loading
          loading.value = false;
        });
},
      onCancel: () => { return},
    });
  } else {
    loading.value = true;
    await createWDTOrder({ orderids: record.id }).then(() => {
      reload();
    }).finally(() => {
      // 这里是无论成功或失败都会执行的方法，在这里关闭loading
      loading.value = false;
    });
  }
  
  
}

async function handleBatchCreateKMOrder() {
  loading.value = true;
  console.log(selectedRowKeys.value);
  
  await createKMOrder({ orderids: selectedRowKeys.value.join(',') }).then( () => {
    reload();
    selectedRowKeys.value = [];
    selectedRows.value = [];
    
  }).finally(() => {
    loading.value = false;
  }
  )

}
async function handleCreateKMOrder(record) {
  if (record.kmSid) {
    createConfirm({
      iconType: 'info',
      title: '重新回传',
      content: '已有kmSid，确定重新回传嘛？',
      onOk: async () => {
        loading.value = true;
        await createKMOrder({ orderids: record.id }).then(() => {
          reload();
        }).finally(() => {
          // 这里是无论成功或失败都会执行的方法，在这里关闭loading
          loading.value = false;
        });
},
      onCancel: () => { return},
    });
  } else {
    loading.value = true;
    await createKMOrder({ orderids: record.id }).then(() => {
      reload();
    }).finally(() => {
      // 这里是无论成功或失败都会执行的方法，在这里关闭loading
      loading.value = false;
    });
  }
  
  
}
/**
 * 下拉操作栏
 */
function getDropDownAction(record) {
  return [
  
    {
      label: '发起售后',
      //ifShow: record.aftersaleCnt < 1,//没有发起售后的
      onClick: handleAddAftersale.bind(null, record)
    },
    {
      label: '刷新订单收货状态',
      onClick: handleRefreshLogistics.bind(null, record,handleSuccess),
      auth: 'slt:orderquery:handleRefreshLogistics',
      
    },
    // {
    //   label: '日志',
    //   onClick: handleLog.bind(null, record),
    //   auth: 'slt:log:query',
      
    // },
    // {
    //   label: '复制新建',
    //   onClick: handleCopyToCreate.bind(null, record),
    // },
    {
      label: '删除',
      onClick: handleDelete.bind(null, record),
      auth: 'slt:orderquery:delete',
      ifShow: record.auditState == '-1' || record.auditState == '0',
      
    },
    {
      label: '删除',
      onClick: handleDelete.bind(null, record),
      auth: 'slt:orderquery:delete2',
      ifShow: record.auditState == '-1' || record.auditState == '0' || record.auditState == '1',

    },
    {
      label: '出库单导出',
      onClick: handleExcelConfigId.bind(null, record, '1011051575872913408', record.orderCode+"出库单"),
      auth: 'lx:xl_customer_orde:pdfExport'
    },
    
    {
      label: '支付凭证',
      ifShow:  (record.isDebt === "欠款送审"),
      onClick: handleSubmitPayment.bind(null, record),
      auth: 'lx:xl_customer_orde:submitPayment'
    },
    {
      label: '上传对账单',
      onClick: handleUploadStament.bind(null,record),
      auth: 'slt:orderquery:uploadstatement1'
    },
    {
      label: '物流查询',
      ifShow: false, //必须是已发货和快递类型的订单
      onClick: handleQueryTrack.bind(null, record),
      auth: 'lx:xl_customer_orde:logisticsQuery1'
    },
    {
      label: '推送收款账单',
      onClick: handlepPayMsg.bind(null, record),
      auth: 'slt:orderquery:pushstatement1'
    },
  ]
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
function isValidTimeRange(start,end){
  if (!start || !end) return false;
  const ONE_DAY_MILLISECOND = 24 * 60 * 60 * 1000;
  const diff = (end.getTime() - start.getTime()) / ONE_DAY_MILLISECOND;;
  return diff <= 30 && diff >= 0;
}
/**
   * 导出事件
   */
function exportOrderXls(btntype) {
  //exportLoading.value=true;
  console.log(selectedRowKeys.value)
  let {getFieldsValue} = getForm();
  let queryData = getFieldsValue();
  if(!queryData.orderCode){
    //如果订单编号没有输入，时间阶段必填
    // if( !queryData.createTime_end ||   !queryData.createTime_end){
    //   createMessage.error("导出支持 30 天内的数据，请选择订单创建时间");
    //   return;
    // }
    // const ONE_DAY_MILLISECOND = 24 * 60 * 60 * 1000;
    //let diff =  (end.getTime() - begin.getTime()) / ONE_DAY_MILLISECOND;
    //创建时间
    let createTime_end = new Date(queryData.createTime_end);
    let createTime_begin = new Date(queryData.createTime_begin);
    //支付时间
    let paymentTime_end = new Date(queryData.paymentTime_end);
    let paymentTime_begin = new Date(queryData.paymentTime_begin);
    //审核时间
    let auditTime_end = new Date(queryData.auditTime_end);
    let auditTime_begin = new Date(queryData.auditTime_begin);

    if(isValidTimeRange(createTime_begin,createTime_end)){

    }else if(isValidTimeRange(paymentTime_begin,paymentTime_end)){

    }else if(isValidTimeRange(auditTime_begin,auditTime_end)){

    }else{
      createMessage.error("至少选择一个时间范围，且时间范围不得超过 30 天");
      return;
    }
    
  }else{
     //如果输了订单单号，创建时间非必填
  }

  let params;
  if(btntype == 1){
    params = Object.assign(getFieldsValue(), {id: selectedRowKeys.value?.join(',')},{exportOnlyOrder: false});
  }
  if(btntype == 2){
    params = Object.assign(getFieldsValue(), {id: selectedRowKeys.value?.join(',')},{exportOnlyOrder: true});
  }
  return handleExportXls("订单数据", "/xl/xlCustomerOrde/exportOrder", params);//getForm().getFieldsValue()
}

import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
function copys(text) {
  const { isSuccessRef } = useCopyToClipboard(text);
  //console.log(isSuccessRef);
  createMessage.info("复制成功");
}
import { defHttp } from '/@/utils/http/axios';
//推送收款账单
async function handlepPayMsg(record) {
  createConfirm({
    iconType: 'warning',
    title: '确认推送账单',
    content: '该订单未支付金额是：' + record.totalRealAmount,
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      return defHttp.get({ url: "/slt/xlWxbotGroupMember/sendPayWxMsm", params: { orderCode: record.orderCode, totalRealAmount: record.totalRealAmount } }).then(() => {
        handleSuccess();
      });
    }
  });
}


import uploadStamentModal from './components/uploadStamentModal.vue'
const [registerUploadStamentModal, openUploadStamentModal] = useModal();

//推送收款账单
async function handleUploadStament(record) {
  
  openUploadStamentModal.openModal(true,record);
}
const [submitPaymentModal, submitPaymentUseModal] = useModal();
/**
 * 支付凭证
 */
async function handleSubmitPayment(record) {
  
  submitPaymentUseModal.openModal(true, {
    title: '支付凭证提交',
    record: { id: record.id, orderCode: record.orderCode, totalRealAmount:record.totalRealAmount },
  });
}

</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}
</style>
